package com.lv.suyiyong.hfr.ui

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPStaticUtils
import com.luck.picture.lib.entity.LocalMedia
import com.lv.common.base.BaseActivity
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.YgxNetUtilsKt
import com.lv.common.utils.YgxSpUtils
import com.lv.common.utils.showToast
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.databinding.ActivityConsealSettingDecBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import okhttp3.RequestBody
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/5/6 10:33 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：隐私设置-具体权限设置说明
 */
@Route(path = ARoutUtils.ConsealSettingDecActivity)
class ConsealSettingDecActivity : BaseActivity<ActivityConsealSettingDecBinding>(),
    View.OnClickListener {
    @Autowired(name = "userinfo")
    @JvmField
    var mUserInfo: UserInfo? = null

    @Autowired(name = "mType")
    @JvmField
    var mType: String = ""
    private var openT = true
    private val viewModel: ServiceViewModel by viewModel()
    private val mSelectMedia = mutableListOf<LocalMedia?>()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())

    override fun getLayoutRes() = R.layout.activity_conseal_setting_dec
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@ConsealSettingDecActivity, titleBar)
            titleBar.onClickBackIcon { finish() }
            titleBar.setTitle("隐私设置")
            tvDoSetting.setOnClickListener(this@ConsealSettingDecActivity)
            ivSwichAction.setOnClickListener(this@ConsealSettingDecActivity)
        }
    }


    override fun initConfig() {
        super.initConfig()
        val isrecommend = mUserInfo?.isrecommend
        openT = isrecommend != "0"
        when (mType) {
            "1" -> {
                mBinding.titleBar.setTitle("位置信息")
                mBinding.tvSettingTitle.text = "为什么需要获取我的位置信息?"
                mBinding.tvSettingDetail.text =
                    "我们访问您的位置信息，根据您的位置信息为您提供更契合您需求的店铺、商品等"
            }

            "2" -> {
                mBinding.titleBar.setTitle("相机")
                mBinding.tvSettingTitle.text = "为什么需要获取我的相机?"
                mBinding.tvSettingDetail.text =
                    "我们访问您的相机是为了使您可以使用摄像头进行扫码、拍摄，用于登录或直接拍摄并上传图片或相应分享以及特定场景下经您授权明确知悉的场景"
            }

            "3" -> {
                mBinding.titleBar.setTitle("相册")
                mBinding.tvSettingTitle.text = "为什么需要获取我的相册?"
                mBinding.tvSettingDetail.text =
                    "我们访问您的相册可以帮助您实现您手机中的照片、图片或视频的取用和上传，便于您进行头像更换、 发表评论/分享或与客服沟通时证明您所遇到的问题"
            }

            "4" -> {
                mBinding.titleBar.setTitle("麦克风")
                mBinding.tvSettingTitle.visibility = View.GONE
                mBinding.tvSettingDetail.text =
                    "我们承诺只在为您提供服务所必要的场景中申请获取您设备的麦克风权限。在您同意开启麦克风权限后，只有您主动点击本客户端内麦克风图标时，本客户端才会通过麦克风功能获取语音信息。"
            }

            "5" -> {

                setSwitchButton(openT, mBinding.ivSwichAction)
                mBinding.tvSettingQuestion.visibility = View.GONE
                mBinding.tvDoSetting.visibility = View.GONE
                mBinding.tvDecSetting.visibility = View.GONE
                mBinding.viewLine2.visibility = View.GONE
                mBinding.tvSafeTitle.visibility = View.GONE
                mBinding.tvDecSafe.visibility = View.GONE
                mBinding.viewLine3.visibility = View.GONE
                mBinding.clRecome.visibility = View.VISIBLE
                mBinding.titleBar.setTitle("个性化内容推荐")
                mBinding.tvSettingTitle.text = "个性化推荐"
                mBinding.tvSettingDetail.text =
                    "为了给您提供更贴合您个人需求的个性化商品及服务，提高您的浏览效率及体验，我们可能会使用到您如下信息：您在访问或使用亨富然平台网站或客户端时的服务日志，包括浏览记录、点击查看记录、搜索查询记录、点赞、收藏、关注分享信息、发布信息，以及IP地址、浏览器类型、电信运营商、使用语言、访问日期和时间。您所使用设备相关信息，包括设备型号、操作系统版本、设备设置、MAC地址及IMEI、设备识别码、设备环境、移动应用列表等软硬件特征信息；设备所在位置相关信息（包括您授权的GPS位置以及WLAN接入点、蓝牙和基站等传感器信息）。我们会基于您以上的个人信息提取您的用户画像和需求特征，并向您推荐您可能感兴趣的商品或服务。\n\n如果您对个性化推荐的商品或服务不感兴趣或者不希望我们为您提供个性化推荐的服务，您可以通过下面按钮关闭个性化推荐服务。如果您关闭按钮，您看到的推荐内容相关性可能会降低，如需要您可再次开启"
            }

        }


    }

    private fun setSwitchButton(isOpen: Boolean, ivSwitch: ImageView) {
        if (isOpen) {
            ivSwitch.setImageResource(com.lv.common.R.drawable.icon_blue_switch_open)
        } else {
            ivSwitch.setImageResource(com.lv.common.R.drawable.icon_switch_off)
        }
    }

    override fun initData() {
        super.initData()
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.tv_do_setting -> {
                getAppDetailSettingIntent()
            }

            R.id.iv_swich_action -> {
                mBinding.ivSwichAction.isEnabled = false
                openT = !openT
                setSwitchButton(openT, mBinding.ivSwichAction)
                startLoading()
                val mPartMedia = YgxNetUtilsKt.partFilesToRequestBody(mSelectMedia)
                val partMap = HashMap<String, RequestBody>()
                partMap["userid"] = YgxNetUtilsKt.partToRequestBody(mUserInfo?.id!!)
                partMap["isrecommend"] = YgxNetUtilsKt.partToRequestBody(if (openT) "1" else "0")
                partMap["cpyid"] =
                    YgxNetUtilsKt.partToRequestBody(YgxSpUtils.getString(Constants.KEY_CPYID) ?: "")
                lifecycleScope.launchWhenCreated {
                    val result: DataResult<BaseYgxRsp> =
                        myScope.async { viewModel.updateMyLogo(partMap, mPartMedia) }.await()
                    parseResult(result)
                }
            }


        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<UserInfo> { code, data, message, result ->
                data?.let {
                    UserDbHelper.UpDataUserInfo(this@ConsealSettingDecActivity, data)
                    SPStaticUtils.put(Constants.KEY_SWITCH_T, openT)
//                    mUserInfo?.isrecommend = it?.isrecommend
                    mBinding.ivSwichAction.isEnabled = true
                }

            }
            onBizError<UserInfo> { code, message, data ->
                showToast(message)
            }
        }
    }

    private fun getAppDetailSettingIntent() {
        val intent = Intent()
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        if (Build.VERSION.SDK_INT >= 9) {
            intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
            intent.data = Uri.fromParts("package", packageName, null)
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.action = Intent.ACTION_VIEW
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails")
            intent.putExtra("com.android.settings.ApplicationPkgName", packageName)
        }
        startActivity(intent)
    }


}